<template>
  <el-dialog v-model="dialogFormVisible" :title='title' width="50%" align-center append-to-body :destroy-on-close='true'>
		<!-- :destroy-on-close='true'关闭后数据清空； append-to-body：dailog是否插入body元素上，默认false  -->
		<div class="dialog-content">
			<el-form :model="formData" label-width="120px" style="max-width: 600px;" :rules="rules" :label-position="labelPosition">
				<el-form-item label="主题" prop='message_title'>
					<el-input v-model="formData.message_title" style="width: 448px;" />
				</el-form-item>
				<el-form-item label="发布部门" prop='message_publish_department' v-if="title=='发布公告'||title=='编辑公告' ">
					<el-input v-model="formData.message_publish_department" disabled style="width: 448px;" />
					<!-- <el-select v-model="formData.message_publish_department" placeholder="请选择发布部门">
						<el-option v-for="item in options" :key="item.value" :label="item.value" :value="item.value" />
					</el-select> -->
				</el-form-item>
				<el-form-item label="发布人" prop='message_publish_name'>
					<el-input v-model="formData.message_publish_name" disabled style="width: 448px;" />
				</el-form-item>
				<el-form-item label="接收部门" prop='message_receipt_object' v-if="title=='发布公告'||title=='编辑公告'">
					<el-select v-model="formData.message_receipt_object" placeholder="请选择接收部门">
						<el-option v-for="item in allOptions" :key="item.value" :label="item.value" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="公告等级" prop='message_level' v-if="title=='发布公告'||title=='编辑公告'">
					<el-select v-model="formData.message_level" placeholder="选择公告等级">
						<el-option label="一般" value="一般" />
						<el-option label="重要" value="重要" />
						<el-option label="必要" value="必要" />
					</el-select>
				</el-form-item>
				<el-form-item label="内容" prop='message_content'>
					<div style="border: 1px solid #ccc">
						<!-- wangEditor结构 -->
						<Toolbar style="border-bottom: 1px solid #ccc;width: 550px;" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
						<Editor style="height: 300px; overflow-y: hidden;width:550px;" v-model="valueHtml" :defaultConfig="editorConfig" 
										:mode="mode" @onCreated="handleCreated" />
					</div>
				</el-form-item>
			</el-form>
		</div>

		<template #footer>
			<span class="dialog-footer">
				<el-button type="primary" @click="yes">确定</el-button>
			</span>
		</template>
  </el-dialog>
</template>
 
<script setup lang="ts">
  import { onBeforeUnmount, reactive, ref, shallowRef } from 'vue';
	import '@wangeditor/editor/dist/css/style.css';
	import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
  import { ElMessage } from 'element-plus';
  import { bus } from "@/utils/mitt.js";
  import { getDepartment } from '@/api/setting';
	import { publishMessage, editMessage } from '@/api/message.js';
	import { changeUserReadList, getIdByDep, getDepartmentMsg, setAllDepartment } from '@/api/dep_msg.js';
	import { useMsg } from '@/store/message.js';

  const title = ref()
  const labelPosition = ref('left')
	const msgStore = useMsg()

	// 部门数据,allOptions 包含了 options 的所有选项，并额外包含了一个 "全体成员" 选项
	const options = ref([]) // 不包括全体成员,options 仅包含发布部门的选项，用于“发布部门”字段
	const allOptions = ref([]) // 包括全体成员,包含了所有部门选项以及 "全体成员" 选项，用于“接收部门”字段

	const returnDepartment = async() => {
		const res = await getDepartment()
		const data = []  //  options
		const dataPro = [] // allOptions 全体成员

		for(let i=0; i<res.data.length; i++){
			let obj = {
				value: res.data[i]
			}
			data.push(obj)
			dataPro.push(obj)
		}
		options.value = data
		dataPro.push({value:"全体成员"})
		allOptions.value = dataPro
	}
	returnDepartment()

	bus.on('createMessage', (id : number) => {
		if (id == 1) {
			title.value = "发布公告"
			valueHtml.value = ''
			formData.message_title = ''
		}
		if (id == 2) {
			title.value = "发布系统消息"
			valueHtml.value = ''
			formData.message_title = ''
		}
	})

	bus.on('editMessage', (row : any) => {
		title.value = "编辑公告"
		valueHtml.value = ''
		formData.id = row.id
		formData.message_title = row.message_title
		formData.message_publish_department = row.message_publish_department
		formData.message_publish_name = row.message_publish_name
		formData.message_receipt_object = row.message_receipt_object
		formData.message_level = row.message_level
		formData.message_content = row.message_content
	})

	bus.on('editSystemMessage', (row : any) => {
		title.value = "编辑系统消息"
		valueHtml.value = ''
		formData.id = row.id
		formData.message_title = row.message_title
		formData.message_publish_name = row.message_publish_name
		formData.message_content = row.message_content
	})

  interface FormData {
		id : number;
		message_title : string;
		message_publish_department : string;
		message_publish_name : string;
		message_category : string;
		message_receipt_object : string;
		message_level : string;
		message_content : string;
	}

  // 表单数据
  const formData:FormData = reactive({
		id: 0,
		message_title: '',
		message_publish_department: localStorage.getItem('department'),
		message_publish_name: localStorage.getItem('name'),
		message_category: '',
		message_receipt_object: '',
		message_level: '',
		message_content: '',
	})

  const rules = reactive({
		message_title: [
			{ required: true, message: '请输入公告标题', trigger: 'blur' },
		],
		message_publish_department: [
			{ required: true, message: '请选择发布部门', trigger: 'blur' },
		],
		message_publish_name: [
			{ required: true, message: '请输入发布人', trigger: 'blur' },
		],
		message_receipt_object: [
			{ required: true, message: '请选择的接收对象', trigger: 'blur' },
		],
		message_level: [
			{ required: true, message: '请选择公告等级', trigger: 'blur' },
		],
		message_content: [
			{ required: true, message: '请输入公告内容', trigger: 'blur' },
		],
	})

	const emit = defineEmits(['success'])
	const yes = async () => {
		// 1. 发布公告
		if (title.value == '发布公告') {
			formData.message_category = '公司公告'
			formData.message_content = valueHtml.value
			const res = await publishMessage(formData)
			if (res.data.status == 0) {
				const res2 = await getIdByDep(formData.message_receipt_object)
				if(formData.message_receipt_object === '全体成员'){
					await setAllDepartment(res.data.id)
					msgStore.returnReadList(localStorage.getItem('id'))// ??
				}else{
					for(var i = 0; i < res2.data.ids.length; i++){
						await getDepartmentMsg(res2.data.ids[i], formData.message_receipt_object)
					}
					await changeUserReadList(res.data.id, formData.message_receipt_object) 
					msgStore.returnReadList(localStorage.getItem('id')) // ??
				}
				
				ElMessage({
					message: '发布公告成功',
					type: 'success',
				})
				emit('success')
				dialogFormVisible.value = false
			} else {
				ElMessage.error('发布公告失败')
				dialogFormVisible.value = false
			}
		}

		// 2. 编辑公告
		if (title.value == '编辑公告') {
			const res = await editMessage(formData)
			msgStore.returnReadList(localStorage.getItem('id'))  // ??
			if (res.data.status == 0) {
				ElMessage({
					message: '编辑公告成功',
					type: 'success',
				})
				emit('success')
				dialogFormVisible.value = false
			} else {
				ElMessage.error('编辑公告失败')
				dialogFormVisible.value = false
			}
		}

		// 3. 发布系统消息
		if (title.value == '发布系统消息') {
			if (title.value == '发布系统消息') {
				formData.message_category = '系统消息'
				const res = await publishMessage(formData)
				if (res.data.status == 0) {
					ElMessage({
						message: '发布系统消息成功',
						type: 'success',
					})
					emit('success')
					dialogFormVisible.value = false
				} else {
					ElMessage.error('发布系统消息失败')
					dialogFormVisible.value = false
				}
			}
		}

		// 4. 编辑系统消息
		if (title.value == '编辑系统消息') {
			const res = await editMessage(formData)
			if (res.data.status == 0) {
				ElMessage({
					message: '编辑系统消息成功',
					type: 'success',
				})
				emit('success')
				dialogFormVisible.value = false
			} else {
				ElMessage.error('编辑系统消息失败')
				dialogFormVisible.value = false
			}
		}
	}

	// ------------------------------------------------------------------------------wangEditor编辑器
	const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef Toolbar
	const mode = ref('default')  // mode 的值可以是 'default' 或 'easy'，分别表示默认模式和简易模式
	const valueHtml = ref() // 内容 HTML，使得编辑器的内容可以双向同步到 valueHtml

	const toolbarConfig = {  // :defaultConfig="toolbarConfig"
		excludeKeys: []
	}

	// toolbarConfig包含一个 excludeKeys 数组，这个数组用于指定哪些菜单项会被排除在外
	toolbarConfig.excludeKeys = [
		'blockquote',
		'bgColor',
		'color',
		'group-more-style',
		'fontFamily',
		'bulletedList',
		'numberedList',
		'lineHeight',
		'todo',
		'emotion',
		'insertLink',
		'group-video',
		'insertTable',
		'codeBlock',
		'divider',
		'fullScreen',
		'group-image',
	]

	// 包含 placeholder 和 MENU_CONF 属性，placeholder 用于设置编辑器的占位文本，MENU_CONF 用于配置菜单项的特定行为
	const editorConfig = {  // :defaultConfig="editorConfig"
		placeholder: '请输入内容...',
		MENU_CONF: {}
	}

	// Editor 组件在创建完成后会触发 onCreated 事件，它接收一个参数 editor，这个参数是 Wangeditor 实例，将 editor 实例赋值给 editorRef.value
	const handleCreated = (editor : any) => {
		editorRef.value = editor 
	}

  // ------------------------------------------------------------------------------弹窗开关
	const dialogFormVisible = ref(false)
  // 打开创建管理员的弹窗
  const open = () => {
    dialogFormVisible.value = true
  }
  defineExpose({
    open
  })
	// 组件销毁时，也及时销毁编辑器
	onBeforeUnmount(() => {
		const editor = editorRef.value
		if (editor == null) return
		editor.destroy()
		bus.all.clear()
	})
</script>
 
<style lang="scss" scoped>
	.dialog-content {
		display: flex;
		padding: 20px 30px;
		flex: 1;
		max-height: 800px;
		overflow: auto;
	}

	.el-dialog__body {
		padding: 0;
	}

	.el-input {
		width: 200px;
	}

	.dialog-footer {
		display: flex;
		justify-content: flex-end;
	}

	.el-form-item {
		margin: 16px;
	}

	:deep(.w-e-text-container p) {
		margin: 0;
	}
</style>
